﻿using BZhanHengjicvWPF.Common;
using BZhanHengjicvWPF.Common.Models;
using BZhanHengjicvWPF.Common.Models.Events;
using BZhanHengjicvWPF.Extensions;
using BZhanHengjicvWPF.Services;
using BZhanHengjicvWPF.Views.Dialogs;
using MyToDo.Dtos;
using Prism.Commands;
using Prism.Events;
using Prism.Ioc;
using Prism.Mvvm;
using Prism.Regions;
using Prism.Services.Dialogs;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Reflection.Metadata;
using System.Text;
using System.Threading.Tasks;
using System.Windows;

namespace BZhanHengjicvWPF.ViewModels
{
    public class IndexViewModel : NavigationViewModel
    {

        private readonly IDialogHostService dialog;
        private readonly IToDoService toDoService;
        private readonly IMemoService memoService;
        private readonly IEventAggregator aggregator;
        private readonly IRegionManager regionManager;
        public IndexViewModel(IContainerProvider container, IDialogHostService dialog, IToDoService toDoService, 
            IMemoService memoService,IEventAggregator aggregator) : base(container)
        {
            CreatTaskBars();
            this.dialog = dialog;
            this.toDoService = toDoService;
            this.memoService = memoService;
            this.aggregator = aggregator;
            this.regionManager= container.Resolve<IRegionManager>();
            title = $"你好{AppSession.UserName}今天是:{DateTime.Now.ToString("yyyy-MM-dd")}";
        }


        private SummaryDto summaryDtos;

        public SummaryDto SummaryDtos
        {
            get { return summaryDtos; }
            set { summaryDtos = value; RaisePropertyChanged(); }
        }

        private ObservableCollection<TaskBar> taskBars = new ObservableCollection<TaskBar>();
        /// <summary>
        /// 目录文件
        /// </summary>
        public ObservableCollection<TaskBar> TaskBars
        {
            get { return taskBars; }
            set { taskBars = value; RaisePropertyChanged(); }
        }

        private string title;

        public string Title
        {
            get { return title; }
            set { title = value;RaisePropertyChanged(); }
        }

        public DelegateCommand<string> ExcuteCommand { get { return new DelegateCommand<string>(Excute); } }
        public DelegateCommand<ToDoDto> EditToDoCommand { get { return new DelegateCommand<ToDoDto>(AddToDo); } }
        public DelegateCommand<MemoDto> EditMemoCommand { get { return new DelegateCommand<MemoDto>(AddMemo); } }
        public DelegateCommand<ToDoDto> CompltedCommand { get { return new DelegateCommand<ToDoDto>(Complted); } }
        public DelegateCommand<TaskBar> NavicateCommand { get { return new DelegateCommand<TaskBar>(Navicate); } }
        /// <summary>
        /// 点击方块跳转到指定的页面
        /// </summary>
        /// <param name="bar"></param>
        private void Navicate(TaskBar bar)
        {
           if(string.IsNullOrWhiteSpace(bar.Target)) { return; }
           NavigationParameters naParam=new NavigationParameters();
            if (bar.Title.Equals("已完成")) naParam.Add("Value",2);
            regionManager.Regions[PrismManager.MainViewRegionName].RequestNavigate(bar.Target,naParam);
        }

        private async void Complted(ToDoDto toDoDto)
        {
            var updateResult = await toDoService.UpdateAsync(toDoDto);
            if (updateResult.Status)
            {
                var todo = summaryDtos.Todolist.FirstOrDefault(t => t.Id == toDoDto.Id);
                if (todo != null)
                {

                    summaryDtos.Todolist.Remove(todo);
                    summaryDtos.CompletedCount += 1;
                    summaryDtos.CompletedRatio = (summaryDtos.CompletedCount / (double)summaryDtos.Sum).ToString("0%");
                    this.Refresh();
                }
                aggregator.SendMessage("已完成！","Login");
            }
        }

        private void Excute(string obj)
        {
            switch (obj)
            {
                case "新增代办": AddToDo(null); break;
                case "新增备忘录": AddMemo(null); break;
            }
        }
        /// <summary>
        /// 新增备忘录
        /// </summary>
        /// <param name="model"></param>
        private async void AddMemo(MemoDto model)
        {
            DialogParameters param = new DialogParameters();
            if (model != null) param.Add("Value", model);

            var dialogResult = await dialog.ShowDialog("AddMemoView", param);
            if (dialogResult.Result == ButtonResult.OK)
            {
                try
                {
                    UpdateLoading(true);
                    var memo = dialogResult.Parameters.GetValue<MemoDto>("Value");
                    if (memo.Id > 0)
                    {
                        var updateResult = await memoService.UpdateAsync(memo);
                        if (updateResult.Status)
                        {
                            var memoModel = SummaryDtos.Memolist.FirstOrDefault(x => x.Id.Equals(memo.Id));
                            memoModel.Title = memo.Title;
                            memoModel.Content = memo.Content;
                        }
                    }
                    else
                    {
                        var addResult = await memoService.AddAsync(memo);
                        if (addResult.Status)
                        {
                            summaryDtos.Memolist.Add(memo);
                        }
                    }
                }
                catch (Exception)
                {
                    throw;
                }
                finally
                {
                    UpdateLoading(false);
                }
            }
        }

        private async void AddToDo(ToDoDto model)
        {
            DialogParameters param = new DialogParameters();
            if (model != null) param.Add("Value", model);

            var dialogResult = await dialog.ShowDialog("AddToDoView", param);
            if (dialogResult.Result == ButtonResult.OK)
            {
                try
                {
                    UpdateLoading(true);
                    var todo = dialogResult.Parameters.GetValue<ToDoDto>("Value");
                    if (todo.Id > 0)
                    {
                        var updateResult = await toDoService.UpdateAsync(todo);
                        if (updateResult.Status)
                        {
                            var todoModel = summaryDtos.Todolist.FirstOrDefault(x => x.Id.Equals(todo.Id));
                            if (todoModel != null)
                            {
                                todoModel.Content = todo.Content;
                                todoModel.Title = todo.Title;
                            }
                        }
                    }
                    else
                    {
                        var addResult = await toDoService.AddAsync(todo);
                        if (addResult.Status)
                        {
                            SummaryDtos.Sum += 1;
                            SummaryDtos.Todolist.Add(addResult.Result);
                            SummaryDtos.CompletedRatio = ((summaryDtos.CompletedCount) / (double)summaryDtos.Sum).ToString("0%");
                            this.Refresh();
                        }

                    }
                }
                catch (Exception ex)
                {
                }
                finally { UpdateLoading(false); }
            }
        }

        public void CreatTaskBars()
        {
            TaskBars.Add(new TaskBar() { Icon = "ClockFast", Title = "汇总", Color = "#ff0ca0ff", Target = "ToDoView" });
            TaskBars.Add(new TaskBar() { Icon = "ClockCheakOutline", Title = "已完成", Color = "#ff1eca3a", Target = "ToDoView" });
            TaskBars.Add(new TaskBar() { Icon = "ChartLineVariant", Title = "完成比例", Color = "#ff02c6dc", Target = "" });
            TaskBars.Add(new TaskBar() { Icon = "PlaylistStar", Title = "备忘录", Color = "#ffffa000", Target = "MemoView" });
        }

        void Refresh()
        {
            taskBars[0].Content = summaryDtos.Sum.ToString();
            taskBars[1].Content = summaryDtos.CompletedCount.ToString();
            taskBars[2].Content = summaryDtos.CompletedRatio.ToString();
            taskBars[3].Content = summaryDtos.MemoCount.ToString();
        }

        public override async void OnNavigatedTo(NavigationContext navigationContext)
        {
            var summaryResult = await toDoService.SummaryAsync();
            if (summaryResult.Status )
            {
                SummaryDtos = summaryResult.Result;
                this.Refresh();
            }
            base.OnNavigatedTo(navigationContext);
        }
    }
}
